package br.com.octobite.cashkeeper;

import java.util.List;

import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import br.com.octobite.cashkeeper.dao.CategoriaDAO;
import br.com.octobite.cashkeeper.dialog.AddCategoriaDialog;
import br.com.octobite.cashkeeper.dialog.DialogListener;
import br.com.octobite.cashkeeper.model.Categoria;

public class CadastraGastosActivity extends Activity implements DialogListener {
	private Spinner spinner;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cadastro_gastos);
		spinner = (Spinner) findViewById(R.id.categorias);
		reloadLista();
	}

	public void adicionaCategoria(View v) {
		FragmentManager fm = getFragmentManager();
		AddCategoriaDialog dialog = new AddCategoriaDialog();
		dialog.show(fm, "dialog");
	}

	@Override
	public void reloadLista() {

		CategoriaDAO dao = new CategoriaDAO(this);
		List<Categoria> listaCategorias = dao.getCategorias();
		dao.close();

		ArrayAdapter<Categoria> adapter = new ArrayAdapter<Categoria>(this,	android.R.layout.simple_spinner_item, listaCategorias);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);

	}

	@Override
	public void salvaCategoria(String nome) {
		final String n = nome;

		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Categoria c = new Categoria();
				c.setNome(n);
				CategoriaDAO dao = new CategoriaDAO(CadastraGastosActivity.this);
				dao.salva(c);
				dao.close();
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						reloadLista();
					}
				});
			}
		}).start();

	}

}
